import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.logging.Logger;

public class AddToCartServlet extends HttpServlet {
    private static final Logger logger = Logger.getLogger(AddToCartServlet.class.getName());

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String goodsId = request.getParameter("goods_id");
        String userId = (String) request.getSession().getAttribute("user_id"); // 假设用户ID存储在session中

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 在这里指定时区
            String url = "jdbc:mysql://localhost:3306/shop?serverTimezone=Asia/Shanghai&useSSL=false"; // 指定时区为上海
            conn = DriverManager.getConnection(url, "root", "123456");
            conn.setAutoCommit(false); // 开始事务 // 开始事务

            String checkSql = "SELECT * FROM car WHERE userid = ? AND goods_id = ?";
            pstmt = conn.prepareStatement(checkSql);
            pstmt.setString(1, userId);
            pstmt.setString(2, goodsId);
            rs = pstmt.executeQuery();

            logger.info("Checking if item is already in cart...");
            if (rs.next()) {
                String updateSql = "UPDATE car SET quantity = quantity + 1 WHERE userid = ? AND goods_id = ?";
                pstmt = conn.prepareStatement(updateSql);
                pstmt.setString(1, userId);
                pstmt.setString(2, goodsId);
                int updated = pstmt.executeUpdate();
                if (updated == 0) {
                    throw new SQLException("更新失败，没有找到对应的记录");
                }
                logger.info("Updated cart item quantity.");
            } else {
                String insertSql = "INSERT INTO car (userid, goods_id, goods_name, unitprice, quantity, pic) VALUES (?, ?, ?, ?, 1, ?)";
                pstmt = conn.prepareStatement(insertSql);
                pstmt.setString(1, userId);
                pstmt.setString(2, goodsId);

                // 从goods表中获取商品详情
                String getGoodsDetailsSql = "SELECT goods_name, unitprice, photo FROM goods WHERE goods_id = ?";
                pstmt = conn.prepareStatement(getGoodsDetailsSql);
                pstmt.setString(1, goodsId);
                ResultSet rsDetails = pstmt.executeQuery();
                if (rsDetails.next()) {
                    String goodsName = rsDetails.getString("goods_name");
                    String unitPrice = rsDetails.getString("unitprice");
                    String pic = rsDetails.getString("photo");
                    pstmt = conn.prepareStatement(insertSql);
                    pstmt.setString(1, userId);
                    pstmt.setString(2, goodsId);
                    pstmt.setString(3, goodsName);
                    pstmt.setString(4, unitPrice);
                    pstmt.setString(5, pic);
                    int inserted = pstmt.executeUpdate();
                    if (inserted == 0) {
                        throw new SQLException("插入失败");
                    }
                    logger.info("Inserted new cart item.");
                } else {
                    throw new SQLException("商品详情获取失败");
                }
                rsDetails.close();
            }
            conn.commit(); // 提交事务
            out.print("success");
        } catch (Exception e) {
            logger.severe("Error adding item to cart: " + e.getMessage());
            if (conn != null) {
                try {
                    conn.rollback(); // 事务回滚
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
            out.print("error");
        } finally {
            // 关闭资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}